'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;
const uniID = require('uni-id')
exports.main = async (event, context) => {
	// 阅读记录
	const uniIDIns = uniID.createInstance({
	  context
	})
	event.watcherId = '';
	let payload={};
	 console.log(event,'eeeeeeeeeeeeeeee')
	 if(event.uniIdToken){
		 payload = uniIDIns.checkToken(event.uniIdToken)
		  console.log(payload,'pppppppppppppppppppppp')
		 if (payload.code && payload.code > 0) {
		 	return payload
		 }
		 event.watcherId=payload.uid;
	 }
	
	
	const watchLog = async (res = {}, type = 'watch') => {
		const now = Date.now()
		const watchLogCollection =  db.collection('watchLogs')
		let logData = {
			deviceId: event.deviceId || context.DEVICEID,
			ip: event.ip || context.CLIENTIP,
			type,
			ua: context.CLIENTUA,
			memoryId:event.memoryId,
			watcherId:event.watcherId||'',
			create_date: now
		};
	
		// Object.assign(logData,
		// 	res.code === 0 ? {
		// 		user_id: "res.user_id",
		// 		state: 1
		// 	} : {
		// 		state: 0
		// 	})
		// console.log(res,'sdsdssdsdsd',logData)
		  watchLogCollection.add(logData)
	}
	watchLog()
	
	return await db.collection('memory')
	.aggregate()
	.match(
		{
			_id: event.memoryId,
		}
	)
	.lookup({
		from:'uni-id-users',
		localField:'user_id',
		foreignField:'_id',
		as:'user_id'
	})
	.lookup({
		from:'watchLogs',
		localField:'_id',
		foreignField:'memoryId',
		as:'memoryWatchList'
	})
	.sort(
		{
			publish_date:-1
		}
	)
	.project({
		title:1,
		content:1,
		imgList:1,
		classfy:1,
		classfyLabel:1,
		canComment:1,
		memoryDate:1,
		publish_date:1,
		publish_dateTime:1,
		commentTotal:1,
		'user_id':{
			nickName: 1,
			sex: 1,
			mobile:1,
			avatar:1
		  },
		watchCount:$.size('$memoryWatchList')
	}).end()
	
	
};
